package com.gitee.ice1938.module.admin.app.manage.fun;

import java.text.DecimalFormat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gitee.ice1938.module.admin.app.manage.appversiondetail.AppVersionDetailEntity;
import com.gitee.ice1938.module.admin.app.manage.appversiondetail.AppVersionDetailRepository;
import com.gitee.ice1938.module.admin.sysoption.fun.OptionService;

@Service
public class VersionServiceImpl implements VersionService {
	@Autowired
	private AppVersionDetailRepository appVersionDetailRepository;

	@Autowired
	private OptionService optionService;

	@Override
	public UpdateResult checkVersion(Integer appVersion, String appPackage) {
		UpdateResult rm = null;
		AppVersionDetailEntity detail = appVersionDetailRepository.findLastPublishOne(appPackage);
		if (detail != null) {
			rm = new UpdateResult();
			int publishVersion = detail.getVersionCode();
			rm.setVersionId(detail.getId());
			rm.setAppMd5(detail.getAppMd5());
			rm.setVersionDesc(detail.getVersionDesc());
			rm.setVersionCode(publishVersion);
			rm.setVersionName(detail.getVersionName());
			rm.setAppSize(detail.getAppSize());
			rm.setAppSizeFormat(formatFileSize(detail.getAppSize()));
			optionService.siteurl();
			rm.setApkUrl(optionService.siteurl() + "/appversiondetail/info/" + detail.getId());
			rm.setApkFileUrl(optionService.siteurl() + "/update/apk/" + detail.getId());
			// 版本号相等不需要更新版本
			if (appVersion == publishVersion) {
				rm.setUpdateFlag(false);
				rm.setForce(false);
			} else if (appVersion > publishVersion) {
				// 当前参数版本大于发布最新版本,那么这种情况仅是在测试的情况下才会出现
				rm.setUpdateFlag(true);
				// 不强制更新
				rm.setForce(false);
			} else if (appVersion < publishVersion) {
				// 当前参数版本低于发布最新版本,需要升级提示
				AppVersionDetailEntity appVersiondetail = appVersionDetailRepository.findByAppKeyVersion(appPackage,
				        appVersion);
				rm.setUpdateFlag(true);
				// 是否强制更新取决于appVersion
				rm.setForce(appVersiondetail.getForceFlag());
			}
		}
		if (rm == null) {
			rm = new UpdateResult();
			rm.setUpdateFlag(false);
		}
		return rm;
	}

	private String formatFileSize(long fileS) {// 转换文件大小
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		if (fileS <= 0) {
			fileSizeString = "0B";
		} else if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "K";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "M";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
		return fileSizeString;
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub

	}
}
